<template>
  <div class="problemList bg-f2">
    <div class="problem-R noControlPanel bg-f2 bg-fff">
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="harderBox">
        <el-form-item>
          <el-button :disabled="quanxianBtns.btn1" type="success" size="medium" class="max_btn btnSizeStyle" icon="el-icon-plus" @click="addRole('添加主机备案')">添加主机备案</el-button>
        </el-form-item>
        <el-form-item label="备案人:">
          <el-select
            v-model="harderBox.userName"
            @focus="selectFocus"
            @blur="selectBlur"
            filterable
            remote
            reserve-keyword
            placeholder="请输入"
            clearable
            :remote-method="remoteMethod"
            :loading="userLoading"
          >
            <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" @click.native="selectChange(item)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备案状态:">
          <el-select v-model="harderBox.pingpai" filterable clearable placeholder="请选择">
            <el-option v-for="item in ppmcOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model.trim="harderBox.nameList" clearable prefix-icon="el-icon-search" placeholder="输入序列号" class="search_btn search_icon"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="max_btn2 btnSizeStyle" @click="getList('查询')">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table
        :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
        ref="multipleTable"
        :data="roleList"
        stripe
        border
        highlight-current-row
        style="width: 100%"
        :default-sort="{ prop: 'CJSJ', order: 'descending' }"
        v-loading="tableLoad"
        @select="isCheck"
        @select-all="isCheckAll"
      >
        <!-- 提示语句 -->
        <template slot="empty">{{ tableMessage }}</template>
        <el-table-column type="selection" width="45" :selectable="checkboxT"></el-table-column>
        <el-table-column type="index" label="序号" min-width="50" align="center"></el-table-column>
        <el-table-column prop="sbxlh" label="主机序列号"></el-table-column>
        <el-table-column label="品牌" min-width="80">
          <template>前卫</template>
        </el-table-column>
        <el-table-column prop="xh" label="型号"></el-table-column>
        <el-table-column prop="bazt" label="状态">
          <template slot-scope="scope">
            <el-tag :type="ztType[scope.row.bazt]" size="medium">{{ zt[scope.row.bazt] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="zsxm" label="备案人"></el-table-column>
        <el-table-column label="LAN/IoT状态" width="100">
          <template slot-scope="scope">
            <div v-if="aloneLoading" class="loading1" style="padding: 10px 0">
              <div class="myloading"></div>
              <div class="myloading"></div>
              <div class="myloading"></div>
              <div class="myloading"></div>
              <div class="myloading"></div>
            </div>
            <div v-else>
              <div v-if="Number(scope.row.wlzt) === 1 || Number(scope.row.wlzt) === 2">
                <!-- 1LAN/IoT在线    2LAN/IoT不在线-->
                <el-tooltip class="item" effect="dark" content="LAN网络" placement="top-start">
                  <svg class="iconfont wlzt" aria-hidden="true">
                    <use :xlink:href="`#${Number(scope.row.wlzt) === 1 || Number(scope.row.zxzt) === 0 ? 'el-icon-myLAN_network' : 'el-icon-myLAN_Nonetwork'}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="IoT网络" placement="top-start">
                  <svg class="iconfont wlzt" aria-hidden="true">
                    <use :xlink:href="`#${Number(scope.row.wlzt) === 1 ? 'el-icon-myIoT_network' : 'el-icon-myIoT_Nonetwork'}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
              </div>
              <div v-else>
                <!-- 3LAN在线    4IoT在线 -->
                <el-tooltip class="item" effect="dark" content="LAN网络" placement="top-start">
                  <svg class="iconfont wlzt" aria-hidden="true">
                    <use :xlink:href="`#${Number(scope.row.wlzt) === 3 || Number(scope.row.zxzt) === 0 ? 'el-icon-myLAN_network' : 'el-icon-myLAN_Nonetwork'}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="IoT网络" placement="top-start">
                  <svg class="iconfont wlzt" aria-hidden="true">
                    <use :xlink:href="`#${Number(scope.row.wlzt) === 4 ? 'el-icon-myIoT_network' : 'el-icon-myIoT_Nonetwork'}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="basj" label="添加时间">
          <template slot-scope="scope">{{ scope.row.basj | dateFormat }}</template>
        </el-table-column>
        <el-table-column prop="basj" label="发现时间">
          <template slot-scope="scope">{{ scope.row.fxsj | dateFormat }}</template>
        </el-table-column>
        <el-table-column prop="basj" label="登记时间">
          <template slot-scope="scope">{{ scope.row.djsj | dateFormat }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="150" align="right">
          <template slot-scope="scope">
            <div class="operations">
              <!-- 不可以点击加上 noAction这个类名 -->
              <!-- <el-button type="text" :disabled="scope.row.bazt !== 3" @click="recovery(scope.row)">恢复</el-button>
              <span class="operation"></span>-->
              <!-- 判断 备案状态 、 权限、 网络状态 -->
              <el-button type="text" :disabled="(scope.row.bazt !== 1 && scope.row.bazt !== 3) || quanxianBtns.btn2 || scope.row.wlzt === '' || scope.row.wlzt === 2" @click="pending(scope.row)"
                >资产登记</el-button
              >
              <!-- <el-button type="text" @click="pending(scope.row)">资产登记</el-button> -->
              <span class="operation"></span>
              <el-button type="text" class="Btn_nan" :disabled="scope.row.bazt !== 2" @click="goConfigure(scope.row)">转配置</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row class="page-row">
        <el-col :span="12">
          <el-button type="primary" size="small" class="shoujiBtn btnSizeStyle" :disabled="selectList.length < 1 || quanxianBtns.btn3" @click="findInfor">批量发现</el-button>
        </el-col>
        <el-col :span="12" style="height: 47px; display: table">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { ziC, findUrl, pinT } from '@/utils/allUrl.js'
// import { endLoading } from '@/utils/loading.js'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
import { getUrl } from '@/utils/getUrl.js'
export default {
  data: function () {
    return {
      harderBox: {
        nameList: '',
        pingpai: '',
        userName: '', // 备案人
      },
      userList: [], // 备案人列表
      restaurants: [], // 搜索数组
      states: [], // 展示搜索结果数组
      userLoading: false, // 搜索等待样式
      currentPage: 1,
      pageSize: 10,
      roleList: [],
      total: 0,
      tableLoad: false,
      tableTimer: null,
      tableMessage: '',
      zt: ['搜索中', '已发现', '已登记', '已报废', '未发现'],
      ztType: ['info', '', 'success', 'danger', 'warning'],
      selectList: [],
      ppmcOptions: [
        { value: 0, label: '搜索中' },
        { value: 1, label: '已发现' },
        { value: 2, label: '已登记' },
        // { value: 3, label: '已报废' },
        { value: 4, label: '未发现' },
      ],
      quanxianBtns: {
        btn1: true,
        btn2: true,
        btn3: true,
      },
      aloneLoading: false, // 主机在线动画
      aloneTimeout: null,
    }
  },
  watch: {
    aloneLoading(newVal, oldVal) {
      this.aloneTimeout = setTimeout(() => {
        if (this.aloneLoading) {
          this.aloneLoading = false
        }
      }, timeLoad)
    },
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.roleList = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
  },
  created: function () {
    this.getUserList() // 渲染用户
    // 权限按钮
    this.jurisdictionBtn()
    // 获取数据
    if (JSON.stringify(this.$route.params) !== '{}') {
      this.harderBox.pingpai = this.$route.params.pingpai
      this.harderBox.nameList = this.$route.params.nameList
      this.getList('查询')
    } else {
      this.getList()
    }
  },
  methods: {
    // 获取备案人列表
    async getUserList() {
      const params = new URLSearchParams()
      params.append('TJCX', this.harderBox.userName)
      const { data: res } = await this.$http.post(`${pinT}yonghu/selectYongHu`, params)
      console.log(res)
      res.data.list.forEach((item) => {
        var list_item = {
          label: item.zsxm + (item.lxdh === '' ? '' : `(${item.lxdh})`),
          value: item.id,
          data: item,
        }
        this.states.push(item.zsxm + (item.lxdh === '' ? '' : `(${item.lxdh})`))
        this.restaurants.push(list_item)
        // }
      })
    },
    // 获取焦点
    selectFocus() {
      this.userList = []
    },
    // 失去焦点
    selectBlur() {
      // 收缩展板
    },
    // 远程搜索框
    remoteMethod(query) {
      if (query !== '') {
        this.userLoading = true
        setTimeout(() => {
          this.userLoading = false
          this.userList = this.restaurants.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.userList = []
      }
    },
    // 值改变
    selectChange(item) {
      this.selectedUser = item.data
      console.log(item)
    },
    // 获取按钮权限
    jurisdictionBtn() {
      const menus = JSON.parse(getUrl('jurisdiction'))
      menus.forEach((item) => {
        if (item.qxdm === 'ZCZX_ZJBAGL_ZJBALB') {
          item.children.forEach((item2) => {
            if (item2.qxdm === 'zcba:create') {
              this.quanxianBtns.btn1 = false // 添加主机备案
            } else if (item2.qxdm === 'zcgl:zcba:insertZiChan') {
              this.quanxianBtns.btn2 = false // 资产登记
            } else if (item2.qxdm === 'piliangfaxian') {
              this.quanxianBtns.btn3 = false // 批量发现
            }
          })
        }
      })
    },
    async recovery(row) {
      const params = new URLSearchParams()
      params.append('xlh', row.sbxlh)
      const { data: res } = await this.$http.post(`${ziC}zcbf/recoveryZiChan`, params)
      switch (res.code) {
        case '0000':
          this.harderBox.nameList = ''
          this.harderBox.pingpai = ''
          this.getList()
          this.$message.success(res.message)
          break
        default:
          this.$message.error(res.message)
          break
      }
    },
    // 获取列表网络状态
    async getWlzt(sns) {
      // http://www.hnlot.com.cn:8081/api/v4/clients/
      // https://cmmop.hnlot.com.cn/api/v4/202009200238
      clearTimeout(this.aloneTimeout)
      this.aloneLoading = true
      const string = sns.join(',')
      const { data: res } = await this.$http.get(`api/host/selectHostNETStatusBySN?snStr=${string}`)
      this.aloneLoading = false
      if (res.code !== '0000') {
        return
      }
      this.roleList.forEach((item, index) => {
        for (const k in res.data) {
          if (item.sbxlh === k) {
            item.wlzt = res.data[k]
          }
        }
      })
    },
    async findInfor(row) {
      const list = []
      let jsonPara = {}
      this.selectList.forEach((item) => {
        list.push(item.sbxlh)
      })
      // 获取地址账号密码
      const { data: res } = await this.$http.post(`${pinT}iot/selectLot`)
      switch (res.code) {
        case '0000':
          if (res.data.lon === null) {
            this.selectList = []
            this.$refs.multipleTable.clearSelection()
            // this.$message.error('请到[平台配置-参数配置]进行参数配置')
            this.$alert('本地IoT未配置，请在参数配置中按要求配置')

            return
          }
          jsonPara = {
            mqttServer: res.data.lon.ip,
            mqttPort: res.data.lon.port,
            mqttName: res.data.lon.mqtt_ACCOUNT,
            mqttPassword: res.data.lon.mqtt_PASSWORD,
            list: list,
          }
          this.findSend(jsonPara)
          break
        default:
          this.$message.error(res.message)
          break
      }
    },
    async findSend(jsonPara) {
      var tips = [
        { id: '0000', message: '成功' },
        { id: '0001', message: '失败' },
        { id: '0002', message: '错误' },
        { id: '0003', message: '暂未发现主机，请稍后再试' },
      ]
      // const params = new URLSearchParams()
      // params.append('jsonPara', JSON.stringify(jsonPara))
      const arr = jsonPara.list
      const text = arr.join(',')
      // params.append('mqttPort', jsonPara.mqttPort)
      // params.append('sns')
      const { data: res } = await this.$http.get(`${findUrl}mqtt/toNewMqttServer?mqttServer=${jsonPara.mqttServer}&mqttPort=${jsonPara.mqttPort}&sns=${text}`)
      // console.log(res)
      switch (res) {
        case '0000':
          this.currentPage = 1
          this.pageSize = 10
          this.getList()
          // this.$message({
          //   showClose: true,
          //   message: '操作成功 主机正在重启,等待时间较长请稍后再试!',
          //   type: 'success',
          //   duration: 0,
          // })
          this.$alert('操作成功 主机正在重启,等待时间较长请稍后再试!', '提示', {
            confirmButtonText: '确定',
            confirmButtonClass: 'btnSizeStyle',
            callback: (action) => {},
          })
          break
        default:
          tips.forEach((item) => {
            if (item.id === res) {
              this.$message.error(item.message)
            }
          })
          break
      }
    },
    isCheck(selection, row) {
      this.selectList = selection
    },
    isCheckAll(selection) {
      this.selectList = selection
    },
    checkboxT(row, index) {
      // 0 搜索中  1已发现 2已登记 4未发现
      if (row.bazt === 0 || row.bazt === 4) {
        return true
      } else {
        return false
      }
    },
    pending(row) {
      this.$router.push({
        name: 'keepOnRecord', // 路由
        query: {
          // 传递参数
          content: row.sbxlh,
          title: '添加资产',
          url: 'networkAccessList',
          pingpai: this.harderBox.pingpai,
          nameList: this.harderBox.nameList,
        },
      })
      var date = new Date()
      let hour = date.getHours() // 时
      hour = hour < 10 ? '0' + hour : hour // 如果只有一位，则前面补零
      let minute = date.getMinutes() // 分
      minute = minute < 10 ? '0' + minute : minute // 如果只有一位，则前面补零
      let second = date.getSeconds() // 秒
      second = second < 10 ? '0' + second : second // 如果只有一位，则前面补零
      var nowDate = `${hour}:${minute}:${second}`
      console.log('点击了', nowDate)
    },
    goConfigure(row) {
      // this.$router.push({ path: '/mainboard', query: { sn: row.sbxlh } })
      const tab = JSON.parse(getUrl('menus'))
      tab.forEach((item) => {
        if (item.qxmc === '资产中心') {
          item.children.forEach((item2) => {
            if (item2.qxfwlj === '/mainboard') {
              item2.sn = row.sbxlh
              this.$emit('getSonMessage', item2)
            }
          })
        }
      })
    },
    // 获取数据
    getList(val) {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const { nameList, pingpai, userName } = this.harderBox
      const params = new URLSearchParams()
      this.selectList = []
      if (val === '查询') {
        this.currentPage = 1
      }
      params.append('SBXLH', nameList)
      params.append('BAZT', pingpai)
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      params.append('YHID', userName) // 备案人
      this.setList(params)
    },
    async setList(params) {
      var sns = []
      const { data: res } = await this.$http.post(`${ziC}zcba/list`, params)
      switch (res.code) {
        case '0000':
          res.data.list.forEach((item) => {
            sns.push(item.sbxlh)
            item.wlzt = ''
          })
          // 获取网络状态
          if (sns.length > 0) {
            this.getWlzt(sns)
          }
          this.roleList = res.data.list
          this.total = res.data.countList
          break
        default:
          this.roleList = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
      this.tableLoad = false // 表格加载中样式
    },
    handleSizeChange(newsize) {
      this.currentPage = 1
      this.pageSize = newsize
      this.getList()
    },
    handleCurrentChange(newChange) {
      this.currentPage = newChange
      this.getList()
    },
    // 添加/修改
    addRole(title) {
      this.$router.push({
        name: 'addNetworks',
        query: {
          title: title,
          pingpai: this.harderBox.pingpai,
          nameList: this.harderBox.nameList,
        },
      })
    },
  },
  destroyed() {
    clearTimeout(this.tableTimer)
    var date = new Date()
    let hour = date.getHours() // 时
    hour = hour < 10 ? '0' + hour : hour // 如果只有一位，则前面补零
    let minute = date.getMinutes() // 分
    minute = minute < 10 ? '0' + minute : minute // 如果只有一位，则前面补零
    let second = date.getSeconds() // 秒
    second = second < 10 ? '0' + second : second // 如果只有一位，则前面补零
    var nowDate = `${hour}:${minute}:${second}`
    console.log('销毁了', nowDate)
  },
}
</script>
<style lang="scss" scoped>
.btn_header {
  height: 35px;
  line-height: 33px;
  margin-bottom: 15px;
  > li:first-child {
    margin-left: 0;
  }
  > li {
    float: left;
    margin-left: 10px;
  }
  .max_btn {
    width: 105px;
    height: 34px;
    line-height: 34px;
    padding: 0;
  }
  .search_btn {
    width: 220px;
  }
  .max_btn2 {
    height: 34px;
    line-height: 34px;
    padding: 0 12px;
  }
}
.addMargin {
  height: 55px;
  line-height: 67px;
}
.operation {
  display: inline-block;
  margin: 0 5px;
  height: 10px;
  border-left: 1.5px solid #b3b3b3;
}
.usersNumber {
  color: rgba(46, 146, 247, 1);
}
.el-card {
  margin-top: 15px;
  border-radius: 0;
  .tiIcon {
    font-size: 14px;
    margin-left: 5px;
    cursor: pointer;
  }
}
.pageFloat {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 48px;
}
.wlzt {
  &.iconfont {
    vertical-align: middle;
    margin-right: 10px;
    width: 20px;
    height: 20px;
  }
}
</style>
